package com.fzshang.commen.serviceImpl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.fzshang.commen.bean.*;
import com.fzshang.commen.bean.layuiBean.ResultPage;
import com.fzshang.commen.bean.layuiBean.VoPage;
import com.fzshang.commen.bean.request.Sale;
import com.fzshang.commen.entity.ApiResult;
import com.fzshang.commen.mapper.UserMapper;
import com.fzshang.commen.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzshang.commen.util.data.Date;
import com.fzshang.commen.util.zhifubao.AliPayConfig;
import com.fzshang.commen.util.zhifubao.OrderIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 账户表 服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2020-02-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RoleService roleService;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    UserOrderService userOrderService;
    @Autowired
    AliPayService aliPayService;
    @Autowired
    AliPayConfig aliPayConfig;

    /**
     * @param account
     * @param passWord
     * @return 登陆
     */
    @Override
    public User UserLogin(String account, String passWord) {
        return baseMapper.userLogin(account,passWord);
    }
    /**
     * @param requestUserName
     * @return 判断是否有这个用户名
     */
    @Override
    public User userNameIsNall(String requestUserName) {
        return baseMapper.userNameIsNall(requestUserName);
    }
    /**
     * @param requestUserName
     * @param requestPassWord
     * @return 判断用户名对应的密码是否正确
     */
    @Override
    public User passWordIsNall(String requestUserName, String requestPassWord) {
        return baseMapper.passWordIsNall(requestPassWord,requestUserName);
    }

    /**
     * @return 查询微信用户
     */
    @Override
    public List<Sale> selectMoney() throws Exception {
        //查询当前系统日期所有年份
        List list = Date.getThisYearFirstDayAndTheLastDay();
        List<Sale>  list1 =new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Integer a = baseMapper.selectByTimeSumMoney((String) list.get(i));
            Sale sale = new Sale();
            sale.setNum(a);
            sale.setTime(list.get(i)+"");
            list1.add(sale);
        }
        for (int i = 0; i < list1.size(); i++) {
            if(list1.get(i).getNum()==null){
                list1.get(i).setNum(0);
            }
        }
        return list1;
    }


    /**
     * @param voPage
     * @return 后台查询
     */
    @Override
    public ResultPage<User> selectMyPage(VoPage voPage, User user) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        paramMap.put("account", user.getAccount());
        paramMap.put("nameOfMerchant", user.getNameOfMerchant());
        paramMap.put("merchantContact", user.getMerchantContact());
        paramMap.put("state", user.getState());
        List<User> list = baseMapper.selectMyPage(paramMap);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getOrderState()==null){
                list.get(i).setOrderState(1);
            }
        }
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<User> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    /**
     * @return  添加角色
     */
    public ApiResult saveRole(Long userId, String account){
        String mm = "1,3,4,8,9,10,11";

        Role role = new Role();
        role.setUserId(userId);
        role.setRoleValue(UUID.randomUUID() + "");
        role.setRoleName(account);
        if (roleService.save(role)) {
            RoleUser roleUser = new RoleUser();
            roleUser.setUserId(userId);
            roleUser.setRoleId(role.getId());
            //角色用户关联表
            if (roleUserService.save(roleUser)) {
                String mmIds[] = mm.split(",");
                for (int i = 0; i < mmIds.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMenuId(Long.parseLong(mmIds[i]));
                    roleMenu.setRoleId(role.getId());//角色菜单关联表
                    if (!roleMenuService.save(roleMenu)) {
                        return ApiResult.fail("添加角色失败");
                    }
                }
            }
        }
        return ApiResult.ok();
    }


    /**
     * @return 支付
     */
    public String zfbPay(User user, HttpServletRequest request) throws AlipayApiException {
        //添加订单
        UserOrder userOrder = new UserOrder();
        String oddNumber = OrderIdUtil.gen("ZFB",1L);
        userOrder.setOddNumbers(oddNumber);
        userOrder.setUserId(user.getId());
        userOrder.setState(1);
        userOrder.setCreateTime(System.currentTimeMillis());
        //添加成功
        if(userOrderService.save(userOrder)){
            return aliPayService.MaChinePCPay(user.getSettlementFee(),"入驻费","商品名称",oddNumber);
        }
        return "失败";
    }

    @Override
    public String aliPayNotify(HttpServletRequest request) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(params, aliPayConfig.ALIPAY_PUBLIC_KEY(), aliPayConfig.CHARSET(), aliPayConfig.SIGNTYPE());
        System.out.println("----------支付成功通知验签状态：----------------" + verify_result);
        System.out.println("params:" + params);
        //验签成功
        if (verify_result) {
            //修改订单状态
            Map map = new HashMap();
            map.put("odd_numbers", params.get("out_trade_no"));
            UserOrder userOrder = new ArrayList<UserOrder>(userOrderService.listByMap(map)).get(0);
            userOrder.setState(2);
            userOrder.setMoney(params.get("receipt_amount"));
            userOrderService.updateById(userOrder);
        }
        return "success";
    }


}
